<?php
    include_once("../action/checkAuthenticationAction.php");
    include_once("../service/productService.php");
    include_once("../service/categoryService.php");
    include_once("../service/bannerService.php");
    include_once("../util/constant.php");
    include_once("../util/message.php");
	include_once("../util/authUtil.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Chi tiết banner sản phẩm mới</title>
	<?php 
        include("import-css.php");
        include("import-css-upload.php");
    ?>
</head>
<body>
    <?php include("header.php");?>
    
	<div class="container-fluid">
		<div class="row-fluid">
            <?php include_once("menu.php");?>
			<div id="content" class="span10">
            	<?php
                    $class = null;
                    $message = null;
                    
                    if(isset($_GET["action"])){
                        $action = $_GET["action"];
                        
                        if($action == INSERT_FAILED){
                            $message = $messages["createSpecialProductStatusFailed"];
                            $class = FAILED_MESSAGE_CLASS;
                        } else if($action == INSERT_SUCCESSFULLY){
                            $message = $messages["createSpecialProductStatusSuccessfully"];
                            $class = SUCCESSFULL_MESSAGE_CLASS;
                        } else if($action == UPDATE_SUCCESSFULLY){
                            $message = $messages["editSpecialProductSuccessfully"];
                            $class = SUCCESSFULL_MESSAGE_CLASS;
                        } else if($action == INSERT_FAILED){
                            $message = $messages["editSpecialProductFailed"];
                            $class = FAILED_MESSAGE_CLASS;
                        }
						
						if(isset($class)){
				?>
                			<div id="msg" class="center alert <?php showClass($class);?>"><?php showMessage($message);?></div>
                <?php
						}
                    }
                ?>
                
            	<div class="box">
                	<div class="box-content">
                    	<?php
							if(!authUtil(array("edit new_product_banner","create new_product_banner","view new_product_banner"),$perm_array,false)){
								echo "<script>window.location.href='../admin/index.php';</script>";
							}
						?>
                    	<form id="fileupload" method="post" enctype="multipart/form-data" class="form-horizontal">
                        	<?php
								$newProductBannerId = 0;
								$isEditMode = false;
								$_SESSION["uploadMode"] = UPLOAD_MODE_NEW_PRODUCT_BANNER;
								unset($_SESSION["newProductBannerId"]);
                                $_SESSION["newAction"] = "1";
								
								if(isset($_GET["id"])){
									$newProductBannerId = $_GET["id"];
									$_SESSION["newProductBannerId"] = $_GET["id"];
                                    unset($_SESSION["newAction"]); 
									$isEditMode = true;
									$newProductBannerInfo = findNewProductBannerBy($newProductBannerId);
								}
                            ?>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Loại sản phẩm</label>
                                <div class="controls">
                                    <select name="category" class="selectpicker" onchange="findProduct(this.value, <?php echo $newProductBannerInfo["BANNER_PRO_ID"]!= "" ? $newProductBannerInfo["BANNER_PRO_ID"] : 0;?>, 2)" >
                                        <?php
                                            $categories = getTreeOfCategories(0);
                                            $firstCatId = 0;
                                            $count = 0;
                                            
                                            foreach($categories as $row){
                                                if($count == 0) $firstCatId = $row["id"];
                                                if($row["id"] == $newProductBannerInfo["CAT_ID"]){
                                        ?>
                                                    <option value="<?php echo $row["id"];?>" selected><?php echo $row["name"];?></option>
                                        <?php
                                                } else {
                                        ?>
                                                    <option value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option>
                                        <?php    
                                                }
                                                $count++;
                                            }
                                        ?>
                                    </select>
                                </div>    
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Sản phẩm</label>
                                <div class="controls">
                                    <select name="product" data-rel="chosen" id="product" class="selectpicker" onchange="assignValue(this.value);">
                                        <?php
                                            $products = findProductNotLinkToNewProductBannerBy($firstCatId, isset($newProductBannerInfo["BANNER_PRO_ID"]) ? $newProductBannerInfo["BANNER_PRO_ID"] : 0);
                                            $count = 0;
                                            while($row = mysql_fetch_array($products)){
                                                if($count == 0) {
                                                    $firstProductId = $row["PRO_ID"];
                                                }
                                                
                                                if($newProductBannerInfo["BANNER_PRO_ID"] == $row["PRO_ID"]){
                                        ?>
                                                    <option value="<?php echo $row["PRO_ID"];?>" selected><?php echo $row["PRO_NAME"];?></option>
                                        <?php
                                                } else{
                                        ?>
                                                    <option value="<?php echo $row["PRO_ID"];?>"><?php echo $row["PRO_NAME"];?></option>
                                        <?php
                                                }
                                                $count++;
                                            }
                                        ?>
                                    </select>
                                    <input type="hidden" id="productName" name="hiddenPro"/>
                                </div>    
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Trạng thái</label>
                                <div class="controls">
                                    <select name="status">
                                        <?php
                                            if($newProductBannerInfo["BANNER_STATUS"]!= "" && $newProductBannerInfo["BANNER_STATUS"] == 0){
                                        ?>
                                                <option value="1">Mở</option>
                                                <option value="0" selected>Tắt</option>
                                        <?php
                                            } else{
                                        ?>
                                                <option value="1" selected>Mở</option>
                                                <option value="0">Tắt</option>
                                        <?php
                                            }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Hình đại diện</label>
                                <div class="controls">
                                    <input type="text" name="image" class="input-xlarge focused" value="<?php if($isEditMode) echo $newProductBannerInfo["BANNER_IMG_PATH"];?>"/>
                                    <div>Kích thước: 530 x 506</div>
                                </div>
                            </div>
                            <?php if($isEditMode){?>
                            <div class="control-group">
                                <label class="control-label" for="textarea2">Hình ảnh</label>
                                <div class="controls">
                                    <div class="row fileupload-buttonbar" style="margin: 3px;">
                                        <div class="col-lg-7">
                                            <!-- The fileinput-button span is used to style the file input field as button -->
                                            <span class="btn btn-success fileinput-button">
                                                <i class="glyphicon glyphicon-plus"></i>
                                                <span>Thêm hình</span>
                                                <input type="file" name="files[]">
                                            </span>
                                            <?php
												$require_perm = array("edit new_product_banner");
												if(authUtil($require_perm,$perm_array,true)){
                                        	?>
                                                <button type="submit" class="btn btn-primary start">
                                                    <i class="glyphicon glyphicon-upload"></i>
                                                    <span>Tải hình</span>
                                                </button>
                                            <?php
												}
                                            ?>
                                            <button type="button" class="btn btn-danger delete" onClick="deleteImage('');">
                                                <i class="glyphicon glyphicon-trash"></i>
                                                <span>Xóa</span>
                                            </button>
                                            <input type="checkbox" class="toggle">
                                            <!-- The loading indicator is shown during file processing -->
                                            <span class="fileupload-loading"></span>
                                        </div>
                                        <!-- The global progress information -->
                                        <div class="col-lg-5 fileupload-progress fade">
                                            <!-- The global progress bar -->
                                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                                            </div>
                                            <!-- The extended global progress information -->
                                            <div class="progress-extended">&nbsp;</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php }?>
                            <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
                            <div class="form-actions">
                            	<?php
									if($isEditMode){
                                ?>
                                		<?php
											$require_perm = array("edit new_product_banner");
											if(authUtil($require_perm,$perm_array,true)){
                                        ?>
		                                	<button type="button" class="btn btn-primary" onclick="submitForm('fileupload', '../action/editNewProductBannerAction.php', 'post');">Chỉnh sửa</button>
                            			<?php
											}
                                        ?>
                                <?php
									} else {
                                ?>
                                		<?php
											$require_perm = array("create new_product_banner");
											if(authUtil($require_perm,$perm_array,true)){
                                        ?>
                                		<button type="submit" class="btn btn-primary" onclick="generateImageNames('imgPaths');submitForm('fileupload', '../action/newNewProductBannerAction.php', 'post');">Tạo mới</button>
                                        <?php
											}
                                        ?>
                                <?php
									}
                                ?>
                            </div>
                            	<input type="hidden" value="" id="imgPaths" name="imgPaths"/>
                            	<input type="hidden" value="<?php if($isEditMode) echo $newProductBannerId; ?>" id="newProductBannerId" name="newProductBannerId"/>
                        </form>
                    </div><!--end of box content-->
                </div><!--end of box-->
            </div><!--end of content-->
        </div><!--end of row fluid-->
        <?php include("footer.php");?>
        <!-- The template to display files available for upload -->
		<script id="template-upload" type="text/x-tmpl">
        {% for (var i=0, file; file=o.files[i]; i++) { %}
            <tr class="template-upload fade">
                <td>
                    <span class="preview"></span>
                </td>
                <td>
                    <p class="name">{%=file.name%}</p>
                    {% if (file.error) { %}
                        <div><span class="label label-danger">Lỗi</span> {%=file.error%}</div>
                    {% } %}
                </td>
                <td>
                    <p class="size">{%=o.formatFileSize(file.size)%}</p>
                    {% if (!o.files.error) { %}
                        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
                    {% } %}
                </td>
                
                <td>
                    {% if (!o.files.error && !i && !o.options.autoUpload) { %}
                        <button class="btn btn-primary start" style="visibility: hidden;">
                            <i class="glyphicon glyphicon-upload"></i>
                            <span>Bắt đầu</span>
                        </button>
                    {% } %}
                    {% if (!i) { %}
                        <button class="btn btn-warning cancel">
                            <i class="glyphicon glyphicon-ban-circle"></i>
                            <span>Hủy</span>
                        </button>
                    {% } %}
                </td>
            </tr>
        {% } %}
        </script>
        <!-- The template to display files available for download -->
        <script id="template-download" type="text/x-tmpl">
        {% for (var i=0, file; file=o.files[i]; i++) { %}
            <tr class="template-download fade">
                <td>
                    <span class="preview">
                        {% if (file.url) { %}
                            <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.url%}"></a>
                        {% } %}
                    </span>
                </td>
                <td>
                    <p class="name">
                        {% if (file.url) { %}
                            <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.url?'data-gallery':''%}>{%=file.name%}</a>
                        {% } else { %}
                            <span>{%=file.name%}</span>
                        {% } %}
                    </p>
                    {% if (file.error) { %}
                        <div><span class="label label-danger">Lỗi</span> {%=file.error%}</div>
                    {% } %}
                </td>
                <td>
				<p class="name">
					{% if (file.url) { %}
							<span onclick="$(this).selectText();">{%=file.url%}</span>
					{% } %}
				</p>
			</td>
                <td>
                    {% if (file.deleteUrl) { %}
                        <button onclick="deleteImage('{%=file.name%}');" class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                            <i class="glyphicon glyphicon-trash"></i>
                            <span>Xóa</span>
                        </button>
                        <input type="checkbox" name="delete" value="{%=file.name%}" class="toggle">
                    {% } else { %}
                        <button class="btn btn-warning cancel">
                            <i class="glyphicon glyphicon-ban-circle"></i>
                            <span>Hủy</span>
                        </button>
                    {% } %}
                </td>
            </tr>
        {% } %}
        </script>
    </div><!--end of container fluid-->
    <?php include("import-js.php");?>
    <?php include("import-js-upload.php");?>
    
    <script>
		$(document).ready(function() {                
			$("#fileupload").validate({
                ignore: [],
                rules: {
                    catgory: { required: true },
                    hiddenPro: { required: true }
                },
                
                messages: {
                    catgory: "<?php echo $messages["validation.required"];?>",
                    hiddenPro: "<?php echo $messages["validation.required"];?>"
                }
            });
            
		});
		
		function deleteImage(name){
            var names = new Array();
            
            $('input[name^=delete]').each(function() {
                if($(this).is(':checked')) names.push($(this).val());
            });
            
            var dataString = "name=" + name + "&names=" + names + "&speProId=" + $("#speProId").val();
            
            $.ajax({
                type: "POST",
                url: "../action/ajax/deleteSpecialProductImageProcess.php",
                data: dataString,
                success: function(data){
                    $("#imgPaths").val("");
                }
            });
        }
        
        function findProduct(catId, parentProId, mode){
            var dataString = "catId=" + catId + "&parentProId=" + parentProId + "&mode=" + mode;
            $.ajax({
                type: "POST",
                url: "../action/ajax/findProductByCatgoryProcess.php",
                data: dataString,
                success: function(data){
                    $(".chzn-results").empty();
                    $(".chzn-results").html(data);
                    if(data.length > 2){
                        $(".chzn-single").html("<span>" + $("#product_chzn_o_0").html() + "</span>");
                        assignValue($("#pro_0").val());
                    } else { // blank data
                        assignValue("");
                        $(".chzn-single").html("<span></span>");
                    }
                }
            });
            
        }
        
        function assignValue(value){
            $("#productName").val(value);
        }
		
		// Initialize the jQuery File Upload widget:
		$('#fileupload').fileupload({
			url: '../image/',
			maxFileSize: <?php echo MAX_FILE_SIZE;?>,
			acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
		}).bind('fileuploadalways', function (e, data) {
		    
        }); 
        
        assignValue(<?php echo $firstProductId;?>);
        hideMessage();
    </script>
</body>
</html>